package com.sikaryofficial.backend.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sikaryofficial.backend.constant.MyStatisticsTypeEnum;
import com.sikaryofficial.backend.constant.ReportBusinessTypeEnum;
import com.sikaryofficial.backend.constant.ReportConstant;
import com.sikaryofficial.backend.constant.ReportTypeEnum;
import com.sikaryofficial.backend.domain.dto.req.ReportAcceptReq;
import com.sikaryofficial.backend.domain.dto.req.ReportListReq;
import com.sikaryofficial.backend.domain.dto.req.ReportReq;
import com.sikaryofficial.backend.domain.dto.resp.BrandTasteEvaluateDTO;
import com.sikaryofficial.backend.domain.dto.resp.EvaluateReplyDTO;
import com.sikaryofficial.backend.domain.dto.resp.ReportDTO;
import com.sikaryofficial.backend.domain.dto.resp.StoreListDTO;
import com.sikaryofficial.backend.domain.entity.BrandTasteEvaluate;
import com.sikaryofficial.backend.domain.entity.BrandTasteEvaluateReply;
import com.sikaryofficial.backend.domain.entity.Store;
import com.sikaryofficial.backend.domain.entity.UserReport;
import com.sikaryofficial.backend.domain.entity.UserReportLog;
import com.sikaryofficial.backend.domain.mapping.BrandTasteEvaluateMapping;
import com.sikaryofficial.backend.domain.mapping.EvaluateReplyMapping;
import com.sikaryofficial.backend.domain.mapping.ReportMapping;
import com.sikaryofficial.backend.domain.mapping.StoreMapping;
import com.sikaryofficial.backend.service.IAddressService;
import com.sikaryofficial.backend.service.IBrandTasteEvaluateReplyService;
import com.sikaryofficial.backend.service.IBrandTasteEvaluateService;
import com.sikaryofficial.backend.service.IStoreService;
import com.sikaryofficial.backend.service.IUserReportLogService;
import com.sikaryofficial.backend.service.IUserReportService;
import com.sikaryofficial.backend.service.address.AddressCacheService;
import com.sikaryofficial.backend.service.statistics.MyStatisticsProcessor;
import com.sikaryofficial.backend.service.statistics.MyStatisticsEvent;
import com.sikaryofficial.backend.service.statistics.MyStatisticsWithTenantEvent;
import com.sikaryofficial.backend.service.store.StoreCacheService;
import com.sikaryofficial.backend.service.user.UserCacheService;
import com.sikaryofficial.backend.service.user.UserReportPubService;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.system.api.model.AddressDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.compress.utils.Lists;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author : qinjinyuan
 * @desc : 活动管理服务
 * @date : 2023/10/30 15:39
 */
@Service
@Slf4j
@SuppressWarnings(value = "unchecked")
public class UserReportManager {
    private static final String REPORT_FLAG = "report";
    @Autowired
    private UserReportPubService pubService;
    @Autowired
    private IUserReportService reportService;
    @Autowired
    private IUserReportLogService reportLogService;
    @Autowired
    private MyStatisticsProcessor myListener;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IBrandTasteEvaluateService evaluateService;
    @Autowired
    private IBrandTasteEvaluateReplyService evaluateReplyService;
    @Autowired
    private StoreCacheService storeCacheService;
    @Autowired
    private UserCacheService userCacheService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private AddressCacheService addressCacheService;
    @Autowired
    private DataRemoveManager dataRemoveManager;
    /**
     * 保存举报
     *
     * @param report
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean reportSave(ReportReq report) {
        // 0-自己的内容，不能进行举报
        checkRelationObject(report);
        String remark = report.getRemark();
        report.setRemark(CharSequenceUtil.isBlank(remark) ? ReportTypeEnum.getEnum(report.getReportType()).getDescription() : remark);
        // 1-添加举报信息
        boolean saveFlag = saveReport(report);
        // 2-增加统计信息
        myListener.addMyStatistics(new MyStatisticsEvent(MyStatisticsTypeEnum.REPORT_NUM.getBusinessType(), SecurityUtils.getUserId(), report.getReportId()));
        return saveFlag;
    }

    /**
     * 校验举报对象是否是自己的内容
     *
     * @param report
     */
    private void checkRelationObject(ReportReq report) {
        ReportBusinessTypeEnum reportBusinessTypeEnum = ReportBusinessTypeEnum.getEnum(report.getBusinessType());
        if (Objects.isNull(reportBusinessTypeEnum)) {
            throw new ServiceException("businessType is not exist");
        }
        if (Objects.isNull(SecurityUtils.getUserId())) {
            throw new ServiceException("userid is not exist");
        }
        pubService.checkRelationObject(reportBusinessTypeEnum,report.getRelationId());
    }

    /**
     * 30分钟 如果没有受理，则系统自动受理
     *
     * @return
     */
    public boolean autoProcess() {
        // 需要查询系统有多少 在createTime > 30分钟未处理，统一进行处理
        log.info("start-----------自动处理");
        List<UserReport> reportList = reportService.autoProcessList();
        if (CollUtil.isEmpty(reportList)) {
            log.info("end-----------自动处理集合为空");
            return false;
        }
        CompletableFuture.runAsync(() -> {
            for (UserReport report : reportList) {
                String remark = "We have received your feedback and the platform will continue to pay attention. Once verified, we will handle it strictly!";
                autoCompleteReport(report, remark, null);
            }
        });
        log.info("end-----------自动处理");
        return true;
    }

    /**
     * 举报删除
     *
     * @param reportId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Object removeInfo(Long reportId) {
        // 删除商品举报主表
        reportService.update(new LambdaUpdateWrapper<UserReport>().setSql("  deleted_version = report_id ")
                .set(UserReport::getUpdatedBy, SecurityUtils.getUserId())
                .set(UserReport::getUpdatedTime, new Date())
                .eq(UserReport::getReportId, reportId));
        // 删除日志信息
        reportLogService.update(new LambdaUpdateWrapper<UserReportLog>().setSql("  deleted_version = report_log_id ").set(UserReportLog::getUpdatedBy, SecurityUtils.getUserId()).set(UserReportLog::getUpdatedTime, new Date()).eq(UserReportLog::getReportId, reportId));
        dataRemoveManager.removeStatics(reportId);
        return true;
    }

    /**
     * 举报状态处理
     *
     * @param report
     */
    public void autoCompleteReport(UserReport report, String remark, Long userId) {
        log.info("start---autoCompleteReport---userId:{}", userId);
        // 乐观锁查看：状态为 ACCEPTING ，并且更新成功的数据
        LambdaUpdateWrapper<UserReport> updateWrapper = new LambdaUpdateWrapper<UserReport>()
                .set(UserReport::getReportStatus, ReportConstant.ACCEPTED)
                .set(UserReport::getUpdatedBy, Objects.isNull(userId) ? 0L : userId)
                .set(UserReport::getUpdatedTime, new Date())
                .eq(UserReport::getReportId, report.getReportId())
                .eq(UserReport::getReportStatus, ReportConstant.ACCEPTING)
                .eq(UserReport::getDeletedVersion, 0L);
        boolean updateFlag = reportService.update(updateWrapper);
        // 如果更新失败，则退出流程
        if (!updateFlag) {
            return;
        }
        UserReportLog reportLog = UserReportLog.builder()
                .reportLogId(IdWorker.getId())
                .reportId(report.getReportId())
                .tenantId(report.getTenantId())
                .remark(remark)
                .createdName(Objects.isNull(userId) ? "System" : userId.toString())
                .createdBy(Objects.isNull(userId) ? 0L : userId)
                .createdTime(new Date())
                .build();
        reportLogService.save(reportLog);
        /**
         *   这里的统计，需要统计到个人，所有userId = report.getCreatedBy();
         */
        myListener.addMyStatisticsWithTenant(new MyStatisticsWithTenantEvent(MyStatisticsTypeEnum.REPORT_ACCEPTED_NUM.getBusinessType(), report.getCreatedBy(), report.getReportId(), report.getTenantId()));
        log.info("end---autoCompleteReport--------自动受理");
    }

    private boolean saveReport(ReportReq report) {
        UserReport input = ReportMapping.INSTANCE.coverToEntity(report);
        Long reportId = IdWorker.getId();
        report.setReportId(reportId);
        input.setReportNum(IdWorker.getMillisecond());
        input.setReportId(reportId);
        input.setCreatedName(SecurityUtils.getUsername());
        input.setCreatedBy(SecurityUtils.getUserId());
        input.setCreatedTime(new Date());
        input.setReportStatus(ReportConstant.ACCEPTING);
        return reportService.save(input);
    }

    /**
     * 详细信息
     *
     * @param reportId
     * @return
     */
    public ReportDTO getInfo(Long reportId) {
        UserReport result = reportService.getOne(new LambdaQueryWrapper<UserReport>()
                .eq(UserReport::getReportId, reportId)
                .eq(UserReport::getDeletedVersion, 0L)
                .last(" limit 1"));
        if (Objects.isNull(reportId)) {
            return new ReportDTO();
        }
        ReportDTO reportDTO = ReportMapping.INSTANCE.coverToDTO(result);
        if (Objects.nonNull(reportDTO) && ReportConstant.ACCEPTED.equals(reportDTO.getReportStatus())) {
            // 获取举报日志最新的记录
            List<UserReportLog> reportLogList = reportLogService.list(new LambdaQueryWrapper<UserReportLog>()
                    .eq(UserReportLog::getReportId, reportId)
                    .eq(UserReportLog::getDeletedVersion, 0L)
                    .orderByDesc(UserReportLog::getCreatedTime)
                    .last(" limit 1")
            );
            reportDTO.setReportLogList(ReportMapping.INSTANCE.coverLogToDTOList(reportLogList));
        }
        if (Objects.isNull(reportDTO) || Objects.isNull(reportDTO.getBusinessType())) {
            return new ReportDTO();
        }
        buildOtherInfo(reportDTO);
        return reportDTO;
    }

    /**
     * 构建其他信息
     *
     * @param reportDTO
     */
    private void buildOtherInfo(ReportDTO reportDTO) {
        // 获取店铺信息
        if (ReportBusinessTypeEnum.STORE.getBusinessType().equals(reportDTO.getBusinessType())) {
            reportDTO.setStoreId(reportDTO.getRelationId());
        }
        // 获取评价信息
        if (ReportBusinessTypeEnum.EVALUATE.getBusinessType().equals(reportDTO.getBusinessType())) {
            reportDTO.setEvaluateId(reportDTO.getRelationId());
            BrandTasteEvaluate evaluate = evaluateService.getById(reportDTO.getRelationId());
            Optional.ofNullable(evaluate).ifPresent(s -> reportDTO.setBrandTasteId(s.getBrandTasteId()));
        }
        // 获取评价回复信息
        if (ReportBusinessTypeEnum.EVALUATE_REPLY.getBusinessType().equals(reportDTO.getBusinessType())) {
            reportDTO.setEvaluateReplyId(reportDTO.getRelationId());
            BrandTasteEvaluateReply evaluate1 = evaluateReplyService.getById(reportDTO.getRelationId());
            Optional.ofNullable(evaluate1).ifPresent(s -> reportDTO.setEvaluateId(s.getEvaluateId()));
        }
        // 仿品举报
        if (ReportBusinessTypeEnum.COUNTERFEIT_REPORTING.getBusinessType().equals(reportDTO.getBusinessType())) {
            reportDTO.setAddress(addressService.getAddressById(reportDTO.getAddressId()));
        }
    }

    /**
     * 举报列表
     *
     * @param report
     * @return
     */
    public IPage<ReportDTO> ownerList(ReportListReq report) {
        Page<UserReport> customerPage = new Page<>(report.getPageNum(), report.getPageSize());
        if (Objects.isNull(report.getUserId())) {
            report.setUserId(SecurityUtils.getUserId());
        }
        IPage<UserReport> result = reportService.page(customerPage, new LambdaQueryWrapper<UserReport>()
                .select(UserReport::getReportId, UserReport::getReportNum,
                        UserReport::getStoreName, UserReport::getAddressId, UserReport::getAddressDetail,
                        UserReport::getBusinessType, UserReport::getReportType, UserReport::getReportStatus,
                        UserReport::getCreatedName, UserReport::getRelationId, UserReport::getRemark,
                        UserReport::getCreatedTime,
                        UserReport::getCountry, UserReport::getCounty, UserReport::getArea, UserReport::getCity
                        )
                .eq(UserReport::getDeletedVersion, 0L)
                .eq(UserReport::getCreatedBy, report.getUserId())
                .eq(UserReport::getReportStatus, report.getReportStatus())
                .orderByDesc(UserReport::getCreatedTime));
        if (CollUtil.isEmpty(result.getRecords())) {
            return new Page<>(1, 7, 0);
        }
        IPage<ReportDTO> reportDTOIPage = result.convert(ReportMapping.INSTANCE::coverToDTO);
        List<ReportDTO> reportDTOList = reportDTOIPage.getRecords();
        // 店铺数据
        fillStoreInfo(reportDTOList);
        // 评价数据
        fillEvaluateInfo(reportDTOList);
        // 回复数据
        fillEvaluateReplyInfo(reportDTOList);
        // 仿品举报数据
        fillCounterfeit(reportDTOList);
        return reportDTOIPage;
    }

    /**
     * 举报列表
     *
     * @param req
     * @return
     */
    public IPage<ReportDTO> listPage(ReportListReq req) {
        Page<UserReport> customerPage = new Page<>(req.getPageNum(), req.getPageSize());
        LambdaQueryWrapper<UserReport> queryWrapper = getUserReportLambdaQueryWrapper(req);
        IPage<UserReport> result = reportService.page(customerPage, queryWrapper);
        if (CollUtil.isEmpty(result.getRecords())) {
            return new Page<>(req.getPageNum(), req.getPageSize(), 0);
        }
        IPage<ReportDTO> reportDTOIPage = result.convert(ReportMapping.INSTANCE::coverToDTO);
        List<ReportDTO> reportDTOList = reportDTOIPage.getRecords();
        // 店铺数据
        fillStoreInfo(reportDTOList);
        // 评价数据
        fillEvaluateInfo(reportDTOList);
        // 回复数据
        fillEvaluateReplyInfo(reportDTOList);
        // 仿品举报数据
        fillCounterfeitData(reportDTOList);
        return reportDTOIPage;
    }

    /**
     * 构建分页参数
     *
     * @param req
     * @return
     */
    @NotNull
    private LambdaQueryWrapper<UserReport> getUserReportLambdaQueryWrapper(ReportListReq req) {
        if (Objects.isNull(req.getUserId())) {
            req.setUserId(SecurityUtils.getUserId());
        }
        if (CharSequenceUtil.isBlank(req.getBusinessTypes())) {
            throw new ServiceException("Business type cannot be empty");
        }
        String[] businessTypes = req.getBusinessTypes().split(",");
        List<Integer> businessTypeArr = Lists.newArrayList();
        Arrays.stream(businessTypes).forEach(s -> businessTypeArr.add(Integer.valueOf(s)));

        List<AddressDTO> addressDTOList = addressCacheService.getAllAddressByCountry();
        List<Long> addressIds = addressDTOList.stream().filter(item -> CharSequenceUtil.isNotBlank(req.getCountry()) && item.getCountry().equals(req.getCountry())).filter(item -> CharSequenceUtil.isNotBlank(req.getArea()) && item.getArea().equals(req.getArea())).filter(item -> CharSequenceUtil.isNotBlank(req.getCity()) && item.getCity().equals(req.getCity())).map(AddressDTO::getAddressId).collect(Collectors.toList());
        LambdaQueryWrapper<UserReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(
                        UserReport::getReportId, UserReport::getReportNum, UserReport::getStoreName,
                        UserReport::getAddressId, UserReport::getAddressDetail, UserReport::getBusinessType,
                        UserReport::getReportType, UserReport::getReportStatus, UserReport::getCreatedName,
                        UserReport::getRelationId, UserReport::getFirstName, UserReport::getLastName,
                        UserReport::getCreatedTime)
                .eq(UserReport::getDeletedVersion, 0)
                .in(CollUtil.isNotEmpty(addressIds), UserReport::getAddressId, addressIds)
                .in(UserReport::getBusinessType, businessTypeArr)
                .likeRight(CharSequenceUtil.isNotBlank(req.getReportNum()), UserReport::getReportNum, req.getReportNum());
        if (CharSequenceUtil.isNotBlank(req.getReportPersonName())) {
            queryWrapper.and(
                    i -> i.likeRight(CharSequenceUtil.isNotBlank(req.getReportPersonName()), UserReport::getFirstName, req.getReportPersonName())
                            .or().likeRight(CharSequenceUtil.isNotBlank(req.getReportPersonName()), UserReport::getLastName, req.getReportPersonName())
            );
        }
        if (Objects.nonNull(req.getStartTime()) && Objects.nonNull(req.getEndTime())) {
            queryWrapper.and(i -> i.between(UserReport::getCreatedTime, req.getStartTime(), req.getEndTime()));
        }
        queryWrapper.orderByDesc(UserReport::getCreatedTime);
        return queryWrapper;
    }

    /**
     * 填充仿品举报数据
     *
     * @param reportDTOList
     */
    private void fillCounterfeit(List<ReportDTO> reportDTOList) {
        if (CollUtil.isEmpty(reportDTOList)) {
            return;
        }
        List<Long> reportIdList = reportDTOList.stream().filter(item -> ReportConstant.COUNTERFEIT_REPORTING_TYPE.equals(item.getBusinessType()))
                .map(ReportDTO::getReportId).collect(Collectors.toList());
        if (CollUtil.isEmpty(reportIdList)) {
            return;
        }
        List<Long> addressIds = reportDTOList.stream().map(ReportDTO::getAddressId).collect(Collectors.toList());
        Map<Long, AddressDTO> addressMap = addressService.getAddressByIds(addressIds);
        // 设置remark字段
        Map<Long, Optional<UserReportLog>> reportLogMap = reportLogService.getLatestLogByReportId(reportIdList);
        reportDTOList.forEach(item -> {
            item.setAddress(MapUtils.getObject(addressMap, item.getAddressId()));
            Optional<UserReportLog> reportLog = MapUtils.getObject(reportLogMap, item.getReportId());
            Optional.ofNullable(reportLog).ifPresent(reportLogItem -> item.setRemark(reportLogItem.get().getRemark()));
        });
    }

    private void fillCounterfeitData(List<ReportDTO> reportDTOList) {
        if (CollUtil.isEmpty(reportDTOList)) {
            return;
        }
        List<Long> addressIds = reportDTOList.stream().map(ReportDTO::getAddressId).collect(Collectors.toList());
        Map<Long, AddressDTO> addressMap = addressService.getAddressByIds(addressIds);
        reportDTOList.forEach(item -> {
            // 填充国家和城市
            AddressDTO addressDTO = addressMap.get(item.getAddressId());
            Optional.ofNullable(addressDTO).ifPresent(addressItem -> {
                item.setCountry(addressItem.getCountry());
                item.setCity(addressItem.getCity());
            });
        });
    }

    /**
     * 查询评价数据
     *
     * @param reportDTOList
     */
    private void fillEvaluateReplyInfo(List<ReportDTO> reportDTOList) {
        if (CollUtil.isEmpty(reportDTOList)) {
            return;
        }
        List<Long> relationIdList = reportDTOList.stream().filter(item -> ReportConstant.EVALUATE_REPLY_TYPE.equals(item.getBusinessType()))
                .map(ReportDTO::getRelationId).collect(Collectors.toList());
        if (CollUtil.isEmpty(relationIdList)) {
            return;
        }
        List<BrandTasteEvaluateReply> brandTasteEvaluates = evaluateReplyService.listByIds(relationIdList);
        if (CollUtil.isEmpty(brandTasteEvaluates)) {
            return;
        }
        List<EvaluateReplyDTO> storeListDTOList = EvaluateReplyMapping.INSTANCE.coverListToDTO(brandTasteEvaluates);
        Map<Long, EvaluateReplyDTO> mapObj =
                storeListDTOList.stream()
                        .collect(Collectors.toMap(EvaluateReplyDTO::getEvaluateReplyId, Function.identity(), (k1, k2) -> k1));
        reportDTOList.forEach(item -> {
            if (ReportConstant.EVALUATE_REPLY_TYPE.equals(item.getBusinessType()) && mapObj.containsKey(item.getRelationId())) {
                EvaluateReplyDTO replyDTO = mapObj.get(item.getRelationId());
                item.setEvaluateReplyId(replyDTO.getEvaluateReplyId());
                item.setRemark(replyDTO.getReplyContent());
                item.setCreatedName(replyDTO.getCreatedName());
                item.setCreatedTime(replyDTO.getCreatedTime());
                item.setEvaluateId(replyDTO.getEvaluateId());
            }
        });
    }

    /**
     * 填充评价信息
     *
     * @param reportDTOList
     */
    private void fillEvaluateInfo(List<ReportDTO> reportDTOList) {
        if (CollUtil.isEmpty(reportDTOList)) {
            return;
        }
        List<Long> relationIdList = reportDTOList.stream().filter(item -> ReportConstant.EVALUATE_TYPE.equals(item.getBusinessType()))
                .map(ReportDTO::getRelationId).collect(Collectors.toList());
        if (CollUtil.isEmpty(relationIdList)) {
            return;
        }
        List<BrandTasteEvaluate> brandTasteEvaluates = evaluateService.listByIds(relationIdList);
        if (CollUtil.isEmpty(brandTasteEvaluates)) {
            return;
        }
        List<BrandTasteEvaluateDTO> storeListDTOList = BrandTasteEvaluateMapping.INSTANCE.coverToDTOList(brandTasteEvaluates);
        Map<Long, BrandTasteEvaluateDTO> mapObj =
                storeListDTOList.stream()
                        .collect(Collectors.toMap(BrandTasteEvaluateDTO::getEvaluateId, Function.identity(), (k1, k2) -> k1));
        reportDTOList.forEach(item -> {
            if (ReportConstant.EVALUATE_TYPE.equals(item.getBusinessType()) && mapObj.containsKey(item.getRelationId())) {
                BrandTasteEvaluateDTO brandTasteEvaluateDTO = mapObj.get(item.getRelationId());
                item.setEvaluateId(brandTasteEvaluateDTO.getEvaluateId());
                item.setRemark(brandTasteEvaluateDTO.getRemark());
                item.setCreatedName(brandTasteEvaluateDTO.getCreatedName());
                item.setCreatedTime(brandTasteEvaluateDTO.getCreatedTime());
            }
        });
    }

    /**
     * 填充店铺信息
     *
     * @param reportDTOList
     */
    private void fillStoreInfo(List<ReportDTO> reportDTOList) {
        if (CollUtil.isEmpty(reportDTOList)) {
            return;
        }
        List<Long> relationIdList = reportDTOList.stream().filter(item -> ReportConstant.STORE_EVALUATE_TYPE.equals(item.getBusinessType()))
                .map(ReportDTO::getRelationId).collect(Collectors.toList());
        if (CollUtil.isEmpty(relationIdList)) {
            return;
        }
        List<Store> storeList = storeService.listByIds(relationIdList);
        if (CollUtil.isEmpty(storeList)) {
            return;
        }
        List<StoreListDTO> storeListDTOList = StoreMapping.INSTANCE.coverDtoListToEntity(storeList);
        Map<Long, StoreListDTO> mapObj =
                storeListDTOList.stream()
                        .collect(Collectors.toMap(StoreListDTO::getStoreId, Function.identity(), (k1, k2) -> k1));
        reportDTOList.forEach(item -> {
            if (ReportConstant.STORE_EVALUATE_TYPE.equals(item.getBusinessType()) && mapObj.containsKey(item.getRelationId())) {
                StoreListDTO storeListDTO = mapObj.get(item.getRelationId());
                item.setStoreId(storeListDTO.getStoreId());
                item.setShopAddress(storeListDTO.getAddress());
                item.setImageUrl(storeListDTO.getImageUrl());
                item.setStoreName(storeListDTO.getStoreName());
                item.setDistance(storeCacheService.calculateDtoDistance(storeListDTO, userCacheService.getUserLocalInfo().getLongitude()
                        , userCacheService.getUserLocalInfo().getLatitude()));
            }
        });
    }

    /**
     * 受理
     * <p>
     * 去掉租户过滤条件  @TenantFilter
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean accept(ReportAcceptReq req) {
        UserReport report = reportService.getOne(new LambdaQueryWrapper<UserReport>()
                .eq(UserReport::getReportId, req.getReportId())
                .eq(UserReport::getReportStatus, ReportConstant.ACCEPTING)
                .eq(UserReport::getDeletedVersion, 0L)
        );
        if (Objects.isNull(report)) {
            throw new ServiceException("The report does not exist or has been accepted");
        }
        autoCompleteReport(report, req.getRemark(), SecurityUtils.getUserId());
        return true;
    }
}
